package com.baidu.erp.utils;

import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.InputStream;

public class MybatisUtil {
    private static ThreadLocal<SqlSession> sqlSessions = new ThreadLocal<>();

    private MybatisUtil(){}
    private static SqlSessionFactory factory;//工厂，用于生产sqlSession
     static{
        InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream("mybatis-config.xml");
        factory = new SqlSessionFactoryBuilder().build(is);
     }
    public static SqlSession getsqlSession() {
        SqlSession sqlSession = sqlSessions.get();
        if (sqlSession==null){
            sqlSession  = factory.openSession();
            sqlSessions.set(sqlSession);
        }
        return sqlSession;
    }
}
